//
//  HomeViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/2.
//  Copyright © 2018年 张庆勇. All rights reserved.
#import "HomeViewController.h"
#import "TableViewHeadview.h"
#import "HomeTableViewCell.h"
#import "Y_StockChartViewController.h"
#import "HomeModle.h"
#import "NewsViewController.h"
#import "NewsInfoViewController.h"
#import "AppDelegate.h"
#import "LLWebViewController.h"
#define timeOut 5
#define headViewHeight  142 + UIScreenWidth*260/540 + 110
@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,SRWebSocketDelegate>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic,strong) TableViewHeadview * tableviewHeadView;
@property (nonatomic, strong) UIButton * upButton;
@property (nonatomic, strong) UIButton * downButton;
@property (nonatomic, strong) UIView * buleView;
@property (nonatomic, strong) NSMutableArray * banneArray;
@property (nonatomic, strong) NSMutableArray * banneDataArray;
@property (nonatomic, strong) NSMutableArray * articlelArray;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, strong) NSMutableArray * newsArray;
@property (nonatomic, strong) NSMutableArray * TitlesArray;
@property (nonatomic, strong) NSMutableArray * recommendArray; //新数组交易对
@property (nonatomic, strong) NSMutableArray * oldRecommendArray; //旧交易对数组
@property (nonatomic, strong) NSMutableDictionary * mutableDic; //储存指定资产价格
@property (nonatomic, assign) NSInteger  buttonIndex;
@property (nonatomic, strong) NSMutableArray * socketdataArray;

@property (nonatomic, strong) NoNetworkView * workView;
@property (nonatomic, strong) SRWebSocket *webSocket;

@property (nonatomic,assign)BOOL isGetnews;
@property (nonatomic,assign)BOOL isrecommen;
@property (nonatomic,assign)BOOL isresh; //3秒后可用刷新
@property (nonatomic,assign)NSInteger second;
@property (nonatomic,assign)NSTimer *  countDownTimer;
@end
@implementation HomeViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self statusBarStyleIsDark:[ZBLocalized sharedInstance].StatusBarStyle];
    _second = 0;
    [self.navigationController setNavigationBarHidden:YES animated:NO]; //设置隐藏
    [super viewWillDisappear:animated];
    [self reconnect];
}
- (void)reconnect
{
    _webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:WBSCOKETHOST_IP]];
    _webSocket.delegate = self;
    [_webSocket open];
   
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏
    [super viewWillDisappear:animated];
}
- (void)showAnimation
{
     _tableView.hidden = YES;
    [self showLoadingAnimation];
}
- (void)stopAnimation
{
    
   [self stopLoadingAnimation];
    _tableView.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(valuationMethod) name:ValuationMethodNotificationse object:nil];
    if ([[EXUnit getSite] isEqualToString:@"ZG"])
    {
        [AppDelegate shareAppdelegate].DICKEY = @"CNZ";
    }else if ([[EXUnit getSite] isEqualToString:@"58"] ||
              [[EXUnit getSite] isEqualToString:@"人人币"] ||
              [[EXUnit getSite] isEqualToString:@"ZT"] ||
              
              [[EXUnit getSite] isEqualToString:@"ZGK"]||
              [[EXUnit getSite] isEqualToString:@"GEMEX"]||
              [[EXUnit getSite] isEqualToString:@"GitBtc"]||
              [[EXUnit getSite] isEqualToString:@"Rockex"])
    {
        [AppDelegate shareAppdelegate].DICKEY = @"CNT";
        
    }else if ([[EXUnit getSite] isEqualToString:@"KCoin"])
    {
        [AppDelegate shareAppdelegate].DICKEY = @"CNY";
    }else if ([[EXUnit getSite] isEqualToString:@"BitAladdin"] ||[[EXUnit getSite] isEqualToString:@"Comex"])
    {
         [AppDelegate shareAppdelegate].DICKEY = @"USDT";
        
    }else
    {
        [AppDelegate shareAppdelegate].DICKEY = @"CNT";
    }
    self.navigationItem.title = @"";
    [self.view addSubview:self.tableView];
    if (![[EXUnit getSite] isEqualToString:@"Coinbetter"])
    {
        [self showAnimation];
    }
    self.isrecommen  = YES;
    self.isresh  = NO;
    [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:WBSCOKETHOST_IP]; //开始连接
    _buttonIndex = 0;
    [self refushserverToken];
    [AppDelegate shareAppdelegate].isNoWork = YES;
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable ) {
          
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"transaction_Network") view:kWindow];
            [AppDelegate shareAppdelegate].isNoWork = NO;
            
        }else
        {
            if (![AppDelegate shareAppdelegate].isNoWork) {
                [self refushserverToken];
            }
            [AppDelegate shareAppdelegate].isNoWork = YES;
        }
    }];
    
    
}
//更换汇率
- (void)valuationMethod
{
    NSData *data= [NSJSONSerialization dataWithJSONObject:@{@"method":@"today.subscribe",@"params":self.socketdataArray,@"id":@(998)} options:NSJSONWritingPrettyPrinted error:nil];
    
    if (self.webSocket.readyState == SR_OPEN) {
        [_webSocket send:data];    // 发送数据
        _second = timeOut;
    }
}
//使用GCD实现倒计时
- (void)startTimeGCD {
 
    WeakSelf
    //创建队列(全局并发队列)
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(weakSelf.second >= timeOut){
            //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            //回到主线程更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                
                weakSelf.isresh  = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.isresh  = NO;
            });
            weakSelf.second++;
        }
    });
    dispatch_resume(_timer);
}

- (void)refushserverToken
{
    [self.dataArray removeAllObjects];
    [self.recommendArray  removeAllObjects];
    NSArray * array = [NSArray bg_arrayWithName:FMDBName_Symbol];
    if (array.count>0) {
        [[AppDelegate shareAppdelegate].dataArray addObjectsFromArray:array];
        self.dataArray  = [NSMutableArray arrayWithArray:array];
        [AppDelegate shareAppdelegate].modle = self.dataArray[0];
        for ( HomeModle * modle in array)
        {
            if ([modle.quote_asset isEqualToString:[AppDelegate shareAppdelegate].DICKEY])
            {
                [self.mutableDic setObject:modle.last forKey:modle.base_asset];
            }
            [self.oldRecommendArray addObject:modle.name];
            
            if (modle.recommend.integerValue ==1) {
                [self.recommendArray addObject:modle];
            }

        }
        
       
        
    }
    [self.tableView reloadData];
    [self getSite];
   
}
- (void)getHomeData
{
    [self getbanner];
   
    [self getNews_list];
    
    if (self.dataArray.count>0)
    {
        [HomeViewModel getCurrencyWithDic:@{} url:currency callBack:^(BOOL isSuccess, id callBack) {
            
        }];
        [self getsymbolData];
    }else
    {
        [HomeViewModel getCurrencyWithDic:@{} url:currency callBack:^(BOOL isSuccess, id callBack) {
            [self getsymbolData];
        }];
    }
}
//搜索
- (void)axcBaseClickBaseRightImageBtn:(UIButton *)sender{
}
#pragma mark----Action数据
- (void)getSite
{
    WeakSelf
    [HomeViewModel getSiteWithDic:nil url:site callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess) {
             weakSelf.tableView.hidden = NO;
            [self placeholderViewWithFrame:weakSelf.tableView.frame NoNetwork:NO];
             [weakSelf getHomeData];
        }else
        {
            weakSelf.tableView.hidden = YES;
            [weakSelf placeholderViewWithFrame:weakSelf.tableView.frame NoNetwork:YES];
        }
    }];
   
}
/*获取bannes*/
- (void)getbanner
{
     WeakSelf
    [HomeViewModel getbannerListWithDic:@{@"position":@"home",@"endpoint":@"app"} url:bannerList callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess)
        {
            NSArray * list = callBack;
            [self.banneArray removeAllObjects];
            self.banneDataArray = [BanneModle mj_objectArrayWithKeyValuesArray:list];
            for (BanneModle *banner in self.banneDataArray)
            {
                
                if ([banner.type integerValue] ==1)
                {
                    [weakSelf.banneArray addObject:banner.image];
                }
            }
            
            weakSelf.tableviewHeadView.scrollView.data = weakSelf.banneArray;
        }else
        {
             weakSelf.tableviewHeadView.scrollView.data = weakSelf.banneArray;
        }
    }];
}
/*获取广告*/
- (void)getNews_list
{
    WeakSelf
   
    [HomeViewModel getArticleListWithDic:@{@"type":@"news",@"class_id":@"",@"offset":@(0),@"limit":@(2)} url:articleList callBack:^(BOOL isSuccess, id callBack) {
        [weakSelf.TitlesArray removeAllObjects];
        [weakSelf.newsArray removeAllObjects];
        if (isSuccess)
        {
            weakSelf.newsArray = callBack;
            for (NewsModle *new in  weakSelf.newsArray)
            {
                [self.TitlesArray addObject:[NSString stringWithFormat:@"%@",new.title]];
            }
            weakSelf.isGetnews = YES;
            if ( weakSelf.isGetnews&& weakSelf.dataArray.count >0)
            {
                [self.tableView beginUpdates];
                CGFloat noticeViewHeight;
                if (self.TitlesArray.count == 0) {
                    noticeViewHeight =  0 ;
                }else
                {
                    noticeViewHeight = 29*self.TitlesArray.count + 10;
                }
                [weakSelf.tableviewHeadView getNoticeList:self.TitlesArray];
                if (self.recommendArray.count >=3) {
                    self.tableviewHeadView.height = headViewHeight - (192/2 - noticeViewHeight -10)-16;
                }else
                {
                    self.tableviewHeadView.height = headViewHeight - (192/2 - noticeViewHeight) - 110 -10;
                }
                [weakSelf.tableviewHeadView refushNewsSymbolDataWithArray:self.recommendArray];
                
                self.tableviewHeadView.bgView.height = self.tableviewHeadView.height;
                [self.tableView setTableHeaderView:self.tableviewHeadView];
                [self.tableView endUpdates];
                self.isrecommen = NO;
                
            }
            
        }else
        {
            [weakSelf getNews_list];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
/*获取最新市场价*/
- (void)getsymbolData
{
    WeakSelf
    [HomeViewModel getSymbolDataListWithDic:@{} url:symbolHttp callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess)
        {
            [weakSelf.socketdataArray removeAllObjects];
            [self.socketdataArray removeAllObjects];
            NSArray * array = callBack;
            for (int i=0; i<array.count; i++) {
                SymbolModle * modle =array[i];
                BOOL isbool = [self.socketdataArray containsObject:modle.symbol];
                if (!isbool) {
                    [self.socketdataArray addObject:modle.symbol];
                    [weakSelf.articlelArray addObject:modle];
                }
            }
            
            if (![EXUnit array:weakSelf.oldRecommendArray isEqualTo:weakSelf.socketdataArray]) { //判断两个数组元素是否相同 不相同重新更新本地数据库
                 self.isrecommen = YES;
                [self.recommendArray removeAllObjects]; //清除推荐数据
                [self.dataArray removeAllObjects]; //如果有新币种移除交易对
                [NSArray bg_clearArrayWithName:FMDBName_Symbol]; //清除数据库交易对
                
            }
            [AppDelegate shareAppdelegate].allCurrency = weakSelf.socketdataArray;
            
            [self sendData];
        }
    }];
}
- (void)sendData
{
    NSData *data= [NSJSONSerialization dataWithJSONObject:@{@"method":@"today.subscribe",@"params":self.socketdataArray,@"id":@(998)} options:NSJSONWritingPrettyPrinted error:nil];
    
    if (self.webSocket.readyState == SR_OPEN) {
        [_webSocket send:data];    // 发送数据
        [self stopAnimation];
        [self startTimeGCD]; //倒计时刷新数据
    }
}
- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    [_workView dissmiss];
    if (NoNetwork)
    {
        
        _workView = [[NoNetworkView alloc] initWithFrame:_tableView.frame NoNetwork:NoNetwork];
        WeakSelf
        _workView.buttonclickeBlock = ^(UIButton *button) { //重新加载
            [weakSelf getSite];
        };
        [self.view addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
    
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, IPhoneTop, UIScreenWidth, UIScreenHeight - TABBAR_HEIGHT1 -IPhoneBottom - IPhoneTop)style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CLEARCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor = TABLEVIEWLCOLOR;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"HomeTableViewCell"];
        _tableView.tableHeaderView =self.tableviewHeadView;
        _tableView.hidden = YES;
        
    }
    return _tableView;
}
- (TableViewHeadview*)tableviewHeadView{
    WeakSelf
    if (!_tableviewHeadView) {
        _tableviewHeadView =[[ TableViewHeadview alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, headViewHeight - RealValue_H(196))];
        //        公告列表
        _tableviewHeadView.Advertblock = ^(NSInteger index) {
            
            NewsModle *model = weakSelf.newsArray[index];
            NewsInfoViewController * NoticeDetailsVC = [[NewsInfoViewController alloc] init];
            NoticeDetailsVC.hidesBottomBarWhenPushed = YES;
            NoticeDetailsVC.title = Localized(@"Public_details");
           
            NoticeDetailsVC.newsID = model.id;
            NoticeDetailsVC.titletext = model.title;
            NoticeDetailsVC.time = [EXUnit getTimeFromTimestamp:model.dateline];
            [weakSelf.navigationController pushViewController:NoticeDetailsVC animated:YES];

        };
        _tableviewHeadView.BancelsUrlblock = ^(NSInteger index) {
            if (weakSelf.banneDataArray.count >0)
            {
                BanneModle * banner =  weakSelf.banneDataArray[index];
                if (![NSString isEmptyString:banner.url]) {
                    
                    if ([banner.url_type isEqualToString:@"ad"])
                    {
                        NewsInfoViewController * NoticeDetailsVC = [[NewsInfoViewController alloc] init];
                        NoticeDetailsVC.hidesBottomBarWhenPushed = YES;
                        NoticeDetailsVC.title = Localized(@"Public_details");
                        NSArray *array = [banner.url componentsSeparatedByString:@"/"]; //从字符A中分隔成2个元素的数组
                        NSString * str = array.lastObject;
                        NoticeDetailsVC.newsID = str;
                       
                         NoticeDetailsVC.isHelp = NO;
                        [weakSelf.navigationController pushViewController:NoticeDetailsVC animated:YES];
                    }else
                    {
                        LLWebViewController *webV = [LLWebViewController new];
                        webV.urlStr = banner.url;
                        webV.isPullRefresh = YES;
                        [weakSelf.navigationController pushViewController:webV animated:YES];
                    }
                   
                }
            }
           
        };
        [_tableviewHeadView.newsButton add_BtnClickHandler:^(NSInteger tag) {
            NewsViewController * newslist = [[NewsViewController alloc] init];
            newslist.title = Localized(@"home_announcement");
            [weakSelf.navigationController pushViewController:newslist animated:YES];
            
        }];

    }
    return _tableviewHeadView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (NSMutableArray *)TitlesArray
{
    if (!_TitlesArray) {
        _TitlesArray = [[NSMutableArray alloc]init];
    }
    return _TitlesArray;
}
- (NSMutableArray *)newsArray
{
    if (!_newsArray) {
        _newsArray = [[NSMutableArray alloc]init];
    }
    return _newsArray;
}
- (NSMutableArray *)banneArray
{
    if (!_banneArray) {
        _banneArray = [[NSMutableArray alloc]init];
    }
    return _banneArray;
}
- (NSMutableArray *)banneDataArray
{
    if (!_banneDataArray) {
        _banneDataArray = [[NSMutableArray alloc]init];
    }
    return _banneDataArray;
}
- (NSMutableArray *)articlelArray
{
    if (!_articlelArray) {
        _articlelArray = [[NSMutableArray alloc] init];
    }
    return _articlelArray;
}
- (NSMutableArray *)socketdataArray
{
    if (!_socketdataArray) {
        _socketdataArray = [[NSMutableArray alloc] init];
    }
    return _socketdataArray;
}
- (NSMutableArray *)oldRecommendArray
{
    if (!_oldRecommendArray) {
        _oldRecommendArray = [[NSMutableArray alloc] init];
    }
    return _oldRecommendArray;
}
- (NSMutableArray *)recommendArray
{
    if (!_recommendArray) {
        _recommendArray = [[NSMutableArray alloc] init];
    }
    return _recommendArray;
}
- (NSMutableDictionary *)mutableDic
{
    if (!_mutableDic) {
        _mutableDic = [[NSMutableDictionary alloc] init];
    }
    return _mutableDic;
}
#pragma  mark -----tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 95;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"HomeTableViewCell"];
    cell.modle = self.dataArray[indexPath.row];
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray * titles = @[Localized(@"home_rise"),Localized(@"home_fall")];
    UIView *BgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth,95)];
    BgView.backgroundColor = TABLEVIEWLCOLOR;
    _buleView = [[UIView alloc] initWithFrame:CGRectMake(0, 40 - 4 +20,  17, 3)];
    _buleView.backgroundColor = [ZBLocalized sharedInstance].segmentBaColor;
    _buleView.clipsToBounds = YES;
    [BgView addSubview:_buleView];
    UIView *lightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 10)];
    lightView.backgroundColor = [ZBLocalized sharedInstance].BgViewLightColor;
    [BgView addSubview:lightView];

    UIBezierPath * bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:CGPointMake(0 , 60)];
    [bezierPath addLineToPoint:CGPointMake(UIScreenWidth , 60)];
    CAShapeLayer * shapeLayer = [CAShapeLayer layer];
    shapeLayer.strokeColor = CELLCOLOR.CGColor;
    shapeLayer.fillColor  = [UIColor clearColor].CGColor;
    shapeLayer.path = bezierPath.CGPath;
    shapeLayer.lineWidth = 0.5f;
    [BgView.layer addSublayer:shapeLayer];
    
    CGFloat x = 0.0, y = 20.0, width = 0.0, height = 72/2;
     if ([[EXUnit isLocalizable] isEqualToString:@"ja"])
    {
        x = 10;
        width = 130;
      
    }else
    {
        x = 25/2;
        width = 116/2;
    }
   
    for (int i=0; i<titles.count; i++) {
       
        UIButton * newButton = [[UIButton alloc] initWithFrame:CGRectMake(x +i*(width+15), y,  width, height)];
        [newButton setTitle:titles[i] forState:UIControlStateNormal];
        [newButton setTitleColor:MAINTITLECOLOR forState:UIControlStateSelected];
        [newButton setTitleColor:MAINTITLECOLOR1 forState:UIControlStateNormal];
        [newButton addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        [newButton centerHorizontallyImageAndTextWithPadding:2];
        newButton.tag = i;
        [BgView addSubview:newButton];
        WeakSelf
         newButton.selected = (i == weakSelf.buttonIndex)? YES:NO;
        if (newButton.selected) {
            newButton.titleLabel.font = AutoBoldFont(16);
            _buleView.centerX =  newButton.centerX;
        }else
        {
            newButton.titleLabel.font = AutoBoldFont(14);
        }
    }
    
    UILabel *sybomLable = [[UILabel alloc] initWithFrame:CGRectMake(10, _buleView.bottom +5, 120, 30)];
    sybomLable.textColor = MAINTITLECOLOR1;
    sybomLable.text = Localized(@"home_symbol");
    sybomLable.font = [UIFont systemFontOfSize:12];
    [BgView addSubview:sybomLable];
    
   
    
    UILabel *rangeLable = [[UILabel alloc] initWithFrame:CGRectMake(UIScreenWidth - 90, _buleView.bottom +5, 80, 30)];
    rangeLable.textColor = MAINTITLECOLOR1;
    rangeLable.text = Localized(@"home_high_low");
    rangeLable.font = [UIFont systemFontOfSize:12];
    rangeLable.textAlignment = NSTextAlignmentCenter;
    [BgView addSubview:rangeLable];
    
    UILabel *priceLable = [[UILabel alloc] initWithFrame:CGRectMake(rangeLable.left - 43/2 -150, _buleView.bottom +5, 150, 30)];
    priceLable.textColor = MAINTITLECOLOR1;
    priceLable.text = Localized(@"home_new_price");
    priceLable.textAlignment = NSTextAlignmentRight;
    priceLable.font = [UIFont systemFontOfSize:12];
    [BgView addSubview:priceLable];
   
    return BgView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeModle *modle = self.dataArray [indexPath.row];
    Y_StockChartViewController * Y_StockChartVC = [[Y_StockChartViewController alloc] init];
    Y_StockChartVC.modle = modle;
     Y_StockChartVC.isleftPush = NO;
    [self.navigationController pushViewController:Y_StockChartVC animated:YES];
}
- (void)buttonClick:(UIButton *)buttonClick
{
    WeakSelf
   
    [UIView animateWithDuration:0.2 animations:^{
      
        if (buttonClick.tag==0) {
            weakSelf.buttonIndex = 0;
          
            NSArray *result = [weakSelf.dataArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                HomeModle * modle1 = obj1;
                HomeModle * modle2 = obj2;
                if ([modle1.IncreaseDegree floatValue] < [modle2.IncreaseDegree floatValue])
                {
                    return NSOrderedDescending;
                }
                else
                {
                    return NSOrderedAscending;
                }
            
                
            }];
            weakSelf.dataArray  = [NSMutableArray arrayWithArray:result];
           [self.tableView reloadData];
        }else
        {
             weakSelf.buttonIndex = 1;
                            //对数组进行排序
            NSArray *result = [weakSelf.dataArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            HomeModle * modle1 = obj1;
            HomeModle * modle2 = obj2;
                if ([modle1.IncreaseDegree floatValue] > [modle2.IncreaseDegree floatValue])
                {
                    return NSOrderedDescending;
                }
                else
                {
                    return NSOrderedAscending;
                }
            
            }];
            weakSelf.dataArray  = [NSMutableArray arrayWithArray:result];
            [self.tableView reloadData];
           
        }
       
      
    }];
   
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - SRWebSocketDelegate
///--------------------------------------
// 成功连接
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
   
}
// 断开连接
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
{
    _webSocket = nil;
     [self reconnect];
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(nonnull NSString *)string
{
    NSLog(@"Received \"%@\"", string);
    
}
// 关闭连接
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
{
    NSLog(@"如果过段时间连接断开重新连接保存一直连接状态");
    _webSocket = nil;
    [self reconnect];
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
    NSLog(@"WebSocket received pong");
}
// 接收消息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    
    //收到服务端发送过来的消息
    if ([NSString isEmptyString:message]) {
        return;
    }
    
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message1 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves  error:nil];
    if (! message1[@"error"])
    {
        NSArray * SocketArray = message1[@"params"];
        NSDictionary * data = SocketArray[1];
        NSString * deal = data[@"deal"];
        NSString * volume = data[@"volume"];
        NSString * high = data[@"high"];
        NSString * open = data[@"open"];
        NSString * last = data[@"last"];
        NSString * low = data[@"low"];
        NSString * name =SocketArray[0];
        if (self.dataArray.count == _articlelArray.count)
        {
          [self UpDataSymbolWithDeal:deal volume:volume high:high open:open last:last low:low name:name]; //更新最新交易对
//          [HomeViewModel UpDataFMDBSymbolWithDeal:deal volume:volume high:high open:open last:last low:low name:name];//更新数据库里的交易对
        }else
        {

            [self getSymbolDataWithDeal:deal volume:volume high:high open:open last:last low:low name:name]; //获取最新交易对
        }

        
 
    }
}
// 获取交易对
- (void)getSymbolDataWithDeal:(NSString *)deal
                       volume:(NSString *)volume
                         high:(NSString *)high
                         open:(NSString *)open
                         last:(NSString *)last
                          low:(NSString *)low
                         name:(NSString *)name
{
   
    
    WeakSelf
    [HomeViewModel getFirestSymbolWithArticlelArray:_articlelArray
                                        ataWithDeal:deal
                                             volume:volume
                                               high:high
                                               open:open
                                               last:last
                                                low:low
                                               name:name
                                          dataArray:self.dataArray
                                     recommendArray:self.recommendArray
                                             DICKEY:[AppDelegate shareAppdelegate].DICKEY
                                         mutableDic:self.mutableDic
                                           callBack:^(NSMutableArray *dataArray,
                                                      NSMutableArray *recommendArray,
                                                      NSMutableDictionary *mutableDic)
{
    
    
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataArray = [AppDelegate shareAppdelegate].dataArray =  dataArray;
            self.recommendArray = recommendArray;
            self.mutableDic = mutableDic;
           
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
            [weakSelf.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            if ( weakSelf.isGetnews&& weakSelf.isrecommen)
            {
                [self.tableView beginUpdates];
                CGFloat noticeViewHeight;
                if (self.TitlesArray.count == 0) {
                    noticeViewHeight =  0 ;
                }else
                {
                    noticeViewHeight = 29*self.TitlesArray.count + 10;
                }
                [weakSelf.tableviewHeadView getNoticeList:self.TitlesArray];
                if (self.recommendArray.count >=3) {
                    self.tableviewHeadView.height = headViewHeight - (192/2 - noticeViewHeight -10)-16;
                }else
                {
                    self.tableviewHeadView.height = headViewHeight - (192/2 - noticeViewHeight) - 110 -10;
                }
                [weakSelf.tableviewHeadView refushNewsSymbolDataWithArray:self.recommendArray];
                
                self.tableviewHeadView.bgView.height = self.tableviewHeadView.height;
                [self.tableView setTableHeaderView:self.tableviewHeadView];
                [self.tableView endUpdates];
                weakSelf.isrecommen  = NO;
            }
            
            
        });
        
    }];
    
    
    
}
/*
 跟新最新交易市场变更
 */
- (void)UpDataSymbolWithDeal:(NSString *)deal
                      volume:(NSString *)volume
                        high:(NSString *)high
                        open:(NSString *)open
                        last:(NSString *)last
                         low:(NSString *)low
                        name:(NSString *)name
{
    
  
    WeakSelf
    [HomeViewModel getUpdataSymbolWithArticlelArray:_articlelArray
                                        ataWithDeal:deal
                                             volume:volume
                                               high:high
                                               open:open
                                               last:last
                                                low:low
                                               name:name
                                          dataArray:self.dataArray
                                     recommendArray:self.recommendArray
                                             DICKEY:[AppDelegate shareAppdelegate].DICKEY
                                          isGetnews:self.isGetnews
                                         isrecommen:self.isrecommen
                                  tableviewHeadView:_tableviewHeadView
                                        buttonIndex:_buttonIndex
                                         mutableDic:self.mutableDic
                                           callBack:^(NSMutableArray *dataArray,
                                                      NSMutableArray *recommendArray,
                                                      NSMutableDictionary *mutableDic)  {
                                               
                                               
         weakSelf.dataArray = [AppDelegate shareAppdelegate].dataArray =  dataArray;
         weakSelf.recommendArray = recommendArray;
         weakSelf.mutableDic = mutableDic;
        [AppDelegate shareAppdelegate].dictionary = mutableDic;
         
         dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 处理耗时操作在此次添加
             if (weakSelf.isresh || weakSelf.isrecommen)
             {
                 NSArray *result = [self.dataArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                     HomeModle * modle1 = obj1;
                     HomeModle * modle2 = obj2;
                     if (weakSelf.buttonIndex ==1)
                     {
                         if ([modle1.IncreaseDegree floatValue] > [modle2.IncreaseDegree floatValue])
                         {
                             return NSOrderedDescending;
                         }
                         else
                         {
                             return NSOrderedAscending;
                         }
                     }else
                     {
                         if ([modle1.IncreaseDegree floatValue] < [modle2.IncreaseDegree floatValue])
                         {
                             return NSOrderedDescending;
                         }
                         else
                         {
                             return NSOrderedAscending;
                         }
                     }

                 }];
                 weakSelf.dataArray = [NSMutableArray arrayWithArray:result];
             }

         });
                            
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.isresh)
            { 
                [weakSelf.tableView reloadData];
                weakSelf.second = 0;
                [weakSelf startTimeGCD];
                weakSelf.isresh = NO;
                [NSArray bg_clearArrayWithName:FMDBName_Symbol]; //清除数据库交易对
                [weakSelf.dataArray bg_saveArrayWithName:FMDBName_Symbol]; //数组排序之后添加数据库
                
            }
            
        });
        
    }];

}

@end
